Page({
  data: {
    storeCode: '',
    deviceCode: '',
    batteryOldCode: '',
    batteryNewCode: '',
    batteryId: '',
    isScanBack: false
  },
  onLoad(options) {
    const {
      isScanBack
    } = this.data
    if (isScanBack) {
      this.setData({
        isScanBack: false
      })
      return;
    }
    if (options.batteryId) {
      this.getInfomation(options.batteryId)
    }
  },
  handleScan() {
    const that = this;
    wx.scanCode({
      success: (res) => {
        that.setData({
          batteryNewCode: res.result,
          isScanBack: true
        })
      }
    })
  },
  getInfomation(_id) {
    let that = this
    wx.cloud.database().collection('information')
      .where({
        _id
      })
      .get()
      .then(res => {
        let data = null;
        if (res.data && res.data.length > 0) {
          data = res.data[0]
          that.setData({
            storeCode: data.storeCode,
            deviceCode: data.deviceCode,
            batteryId: data._id,
            batteryOldCode: data.batteryOldCode
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err,
          icon: 'error',
          duration: 2000
        })
      })
  },
  formSubmit(e) {
    if (!e.detail.value.batteryNewCode) {
      return wx.showToast({
        icon: 'none',
        title: '新电池编码不能为空',
      })
    }
    this.update({
      batteryNewCode: e.detail.value.batteryNewCode,
      updatedAt: new Date().getTime(),
    })
  },
  update(data) {
    console.log('编辑信息', data)
    const {
      batteryId
    } = this.data
    wx.cloud.database().collection('information')
      .doc(batteryId)
      .update({
        data
      })
      .then(res => {
        wx.showToast({
          title: '更换成功',
          icon: 'success',
          duration: 2000
        })
        wx.navigateBack();
      }).catch(err => {
        wx.showToast({
          title: err,
          icon: 'error',
          duration: 2000
        })
      })
  }
})